<template>
  <div class="content">
    <Header title="注册用户">
      <div slot="left" @click="goBack" style="width: 100%;height: 100%;text-align: center;">
        <i class="iconfont icon-arrow-left" style="font-size: 22px"></i>
      </div>
    </Header>
    <div class="main">
      <div class="login_content">
        <form @submit.prevent="register">
          <div :class="{on: loginWay}">
            <section class="login_message">
              <input type="tel" maxlength="11" placeholder="手机号" v-model="regphone">
              <button
                :disabled="!rightPhone"
                class="get_verification"
                :class="{right_phone:rightPhone}"
                @click.prevent="getCode"
              >{{computeTime>0 ? `(${computeTime}s)已发送` : '获取验证码'}}</button>
            </section>
            <section class="login_verification">
              <input type="tel" maxlength="6" placeholder="验证码" v-model="regcode">
            </section>
            <section class="login_verification">
              <input type="password" maxlength="20" placeholder="输入密码" v-model="regpwd">
            </section>
            <section class="login_verification">
              <input type="password" maxlength="20" placeholder="确认密码" v-model="regrpwd">
            </section>
            <button class="login_submit">账户注册</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>
<script>
import {
  reqSendCode,
  reqWechartLogin,
  reqMemberRegister
} from "../../api/index.js";
import { getUrlAllParams, decodeUnicode, isWeiXin } from "../../util/unit.js";
import { mapState } from "vuex";
import Header from "../../components/Header/Header";
export default {
  data() {
    return {
      wechartInfo: {},
      loginWay: true, // true注册, false登录
      computeTime: 0,
      regphone: "", //注册手机号
      regcode: "", //注册验证码
      regpwd: "", //注册密码
      regrpwd: "" //注册密码确认
    };
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      let code = getUrlAllParams() && getUrlAllParams().code;
      // 在微信环境下
      if (isWeiXin() && !code) {
        console.log("微信环境且code不存在");
        vm.wechartLogin();
      }
      if (isWeiXin() && code) {
        vm.getInfoByWechart(code);
      }
    });
  },
  computed: {
    ...mapState(["curUrl"]),
    rightPhone() {
      // 利用正则对手机号进行匹配，返回布尔值
      return /^1\d{10}$/.test(this.regphone);
    }
  },
  methods: {
    goBack() {
      if (window.history.length <= 1) {
        this.$router.push({ path: "/" });
        return false;
      } else {
        this.$router.go(-1);
      }
    },
    // 异步获取短信验证码
    async getCode() {
      if(this.computeTime){
        console.log("还在计时中,不能发送!")
        return;
      }
      // 如果当前没有计时!this.computeTime等于this.computeTime === 0
      if (!this.computeTime) {
        // 启动倒计时
        this.computeTime = 30;
        this.intervalId = setInterval(() => {
          this.computeTime--;
          if (this.computeTime <= 0) {
            // 停止计时
            clearInterval(this.intervalId);
          }
        }, 1000);
      }
      // 发送ajax请求（向指定手机号发送验证码短信）
      const result = await reqSendCode({
        mobile: this.regphone,
        event: "register"
      });
      if (result.code === 1) {
        // if (this.computeTime) {
          this.$vux.toast.show(`发送验证码成功:${result.msg}`);
        // }
      } else {
        this.computeTime = 0;
        clearInterval(this.intervalId);
        this.intervalId = undefined;
        this.$vux.toast.show(`获取验证码失败:${result.msg}`);
      }
    },
    async getInfoByWechart(code) {
      // 获取微信信息
      const result = await reqWechartLogin({ code: code, scope: "userinfo" });
      console.log("result", result);
      // 根据结果数据处理
      if (result.code === 1) {
        this.wechartInfo = result.data;
      } else {
        // 显示警告提示
        this.$vux.toast.show(`获取微信信息:${result.msg}`);
      }
    },
    // 微信登录
    wechartLogin() {
      let appId = window.global.weChart.appId;
      let appSecret = window.global.weChart.appSecret;
      let token = window.global.weChart.token;
      let encodingAesKey = window.global.weChart.encodingAesKey;
      let redirect_uri = window.global.weChart.redirect_uri_register;
      let url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;
      window.location.href = url;
    },
    // 注册
    async register() {
      // 验证
      if (this.regpwd !== this.regrpwd) {
        this.$vux.toast.show("注册密码必须与确认密码相同!");
        return;
      }
      if (!this.regphone || !this.regpwd || !this.regrpwd || !this.regcode) {
        this.$vux.toast.show("所有参数必须全部填写!");
        return;
      }
      if (!this.wechartInfo || !this.wechartInfo.openId) {
        this.$vux.toast.show("微信还未授权!");
        this.wechartLogin();
        return;
      }
      let query = {
        openId: this.wechartInfo.openId,
        mobile: this.regphone,
        password: this.regpwd,
        captcha: this.regcode,
        nickName: this.wechartInfo.nickName,
        avatar: this.wechartInfo.headImgUrl,
        gender: this.wechartInfo.sex,
        groupId: 0
      };
      let result = await reqMemberRegister(query);
      if (result.code === 1) {
        this.$vux.toast.show("注册成功!");
        window.location.href =
          window.location.origin + window.location.pathname + "#/login";
      } else {
        this.$vux.toast.show(`注册失败:${result.msg}`);
      }
    }
  },
  components: { Header }
};
</script>
<style lang='less' scoped>
@import "../../util/theme.less";

.content {
  .be-full();
  .main {
    width: 100%;
    height: calc(~"100% - 46px");
    .mix-flex-center();
    align-items: flex-start;
  }
}

.login_content {
  width: 80%;
  > form {
    > div {
      display: none;

      &.on {
        display: block;
      }

      input {
        width: 100%;
        height: 100%;
        padding-left: 10px;
        box-sizing: border-box;
        border: 1px solid #ddd;
        border-radius: 4px;
        outline: 0;
        font: 400 14px Arial;

        &:focus {
          border: 1px solid @red;
        }
      }

      .login_message {
        position: relative;
        margin-top: 16px;
        height: 48px;
        font-size: 14px;
        background: #fff;

        .get_verification {
          position: absolute;
          top: 50%;
          right: 10px;
          transform: translateY(-50%);
          border: 0;
          color: #ccc;
          font-size: 14px;
          background: transparent;

          &.right_phone {
            color: black;
          }
        }
      }

      .login_verification {
        position: relative;
        margin-top: 16px;
        height: 48px;
        font-size: 14px;
        background: #fff;

        .switch_button {
          font-size: 12px;
          border: 1px solid #ddd;
          border-radius: 8px;
          transition: background-color 0.3s, border-color 0.3s;
          padding: 0 6px;
          width: 30px;
          height: 16px;
          line-height: 16px;
          color: #fff;
          position: absolute;
          top: 50%;
          right: 10px;
          transform: translateY(-50%);

          &.off {
            background: #fff;

            .switch_text {
              float: right;
              color: #ddd;
            }
          }

          &.on {
            background: @red;
          }

          > .switch_circle {
            // transform translateX(27px)
            position: absolute;
            top: -1px;
            left: -1px;
            width: 16px;
            height: 16px;
            border: 1px solid #ddd;
            border-radius: 50%;
            background: #fff;
            box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.1);
            transition: transform 0.3s;

            &.right {
              transform: translateX(14px);
            }
          }
        }
      }

      .login_hint {
        margin-top: 12px;
        color: #999;
        font-size: 14px;
        line-height: 20px;

        > a {
          color: @red;
        }
      }
    }

    .login_submit {
      display: block;
      width: 100%;
      height: 42px;
      margin-top: 30px;
      border-radius: 4px;
      background: @red;
      color: #fff;
      text-align: center;
      font-size: 16px;
      line-height: 42px;
      border: 0;
    }
  }

  .about_us {
    display: block;
    font-size: 12px;
    margin-top: 20px;
    text-align: center;
    color: #999;
  }
}
</style>
